#include "GLES2RenderTexture.h"
#include "GLES2HardwarePixelBuffer.h"

namespace PVM
{
	template<> GLES2RTTManager* Singleton<GLES2RTTManager>::ms_Singleton = 0;
	
	GLES2RTTManager::~GLES2RTTManager()
	{
	}
	
	MultiRenderTarget* GLES2RTTManager::createMultiRenderTarget(const std::string& name)
	{
		PVM_EXCEPT("MultiRenderTarget is not supported",
				   "GLES2RTTManager::createMultiRenderTarget");
	}
	
	PixelFormat GLES2RTTManager::getSupportedAlternative(PixelFormat format)
	{
		if (checkFormat(format))
		{
			return format;
		}
		
		PixelComponentType pct = PixelUtil::getComponenType(format);
		switch(pct)
		{
			case PCT_BYTE:
				format = PF_A8R8G8B8;
				break;
			case PCT_SHORT:
				format = PF_SHORT_RGBA;
				break;
			case PCT_FLOAT16:
				format = PF_FLOAT16_RGBA;
				break;
			case PCT_FLOAT32:
				format = PF_FLOAT32_RGBA;
				break;
			case PCT_COUNT:
			default:
				break;
		}
		
		if (checkFormat(format))
			return format;
		
		return PF_A8R8G8B8;
	}
	
	GLES2RenderTexture::GLES2RenderTexture(const std::string& name,
										   const GLES2SurfaceDesc& target,
										   bool writeGamma,
										   uint fsaa)
	: RenderTexture(target.buffer, target.zoffset)
	{
		mName = name;
		mHwGamma = writeGamma;
		mFSAA = fsaa;
	}
	
	GLES2RenderTexture::~GLES2RenderTexture()
	{
	}
	
	GLES2CopyingRenderTexture::GLES2CopyingRenderTexture(GLES2CopyingRTTManager* manager,
														 const std::string& name,
														 const GLES2SurfaceDesc& target,
														 bool writeGamma, uint fsaa)
	: GLES2RenderTexture(name, target, writeGamma, fsaa)
	{
	}
	
	void GLES2CopyingRenderTexture::getCustomAttribute(const std::string& name, void* pData)
	{
		if (name == "TARGET")
		{
			GLES2SurfaceDesc& target = *static_cast<GLES2SurfaceDesc*>(pData);
			target.buffer = static_cast<GLES2HardwarePixelBuffer*>(mBuffer);
			target.zoffset = mZOffset;
		}
	}
	
	GLES2CopyingRTTManager::GLES2CopyingRTTManager()
	{
	}
	
	GLES2CopyingRTTManager::~GLES2CopyingRTTManager()
	{
	}
	
	RenderTexture* GLES2CopyingRTTManager::createRenderTexture(const std::string& name,
															   const GLES2SurfaceDesc& target,
															   bool writeGamma, uint fsaa)
	{
		return new GLES2CopyingRenderTexture(this, name, target, writeGamma, fsaa);
	}
	
	bool GLES2CopyingRTTManager::checkFormat(PixelFormat format)
	{
		return true;
	}
	
	void GLES2CopyingRTTManager::bind(RenderTarget* target)
	{
	}
	
	void GLES2CopyingRTTManager::unbind(RenderTarget* target)
	{
		GLES2SurfaceDesc surface;
		surface.buffer = 0;
		target->getCustomAttribute("TARGET", &surface);
		if (surface.buffer)
		{
			static_cast<GLES2TextureBuffer*>(surface.buffer)->copyFromFrameBuffer(surface.zoffset);
		}
	}
}
